/*
 * u_slice.h
 *
 *  Created on: 2012-10-6
 *      Author: lin
 */

#ifndef U_SLICE_H_
#define U_SLICE_H_

#include "def/defs.h"

#include "zmalloc/zmalloc.h"
#include "util_string.h"


typedef struct {
    const char* data;
    size_t size;
} u_slice_t;

u_slice_t* u_slice_new0(void);
u_slice_t* u_slice_new1(const char* d, size_t size);
u_slice_t* u_slice_new2(const char* d);

void u_slice_free(u_slice_t *slice);
int u_slice_compare(const u_slice_t* l, const u_slice_t* r);

static inline const char* u_slice_data(const u_slice_t* slice) {
    return slice->data;
}
static inline size_t u_slice_size(const u_slice_t* slice) {
    return slice->size;
}

static inline char u_slice_index(const u_slice_t* slice, size_t idx) {
    assert(idx < slice->size);
    return slice->data[idx];
}

static inline void u_slice_clear(u_slice_t* slice) {
    slice->data = "";
    slice->size = 0;
}

static inline void u_slice_remove_prefix(u_slice_t* slice, size_t n) {
    assert(n <= slice->size);
    slice->data += n;
    slice->size -= n;
}

static inline int u_slice_starts_with(const u_slice_t* slice,
        const u_slice_t* prefix) {
    return string_starts_with0(slice->data, slice->size, prefix->data,
            prefix->size);
}

static inline int u_slice_equals(const u_slice_t* l, const u_slice_t* r) {
    return (l->size == r->size) && memcmp(l->data, r->data, l->size);
}
#endif /* U_SLICE_H_ */
